﻿using Framework;
using Koala.Framework;
using Microsoft.Win32;
using System;
using System.Windows.Forms;

namespace Koala.JiraTool.AutoStart
{
    public class Settings
    {
        public bool IsAutoStart { get; set; }
    }

    public partial class MainControl : UserControl, ITransientDependency
    {
        private readonly IDataPersistence _dataPersistence;

        public MainControl(IDataPersistence dataPersistence)
        {
            _dataPersistence = dataPersistence;
            InitializeComponent();

            var settings = _dataPersistence.Get<Settings>();
            if (settings == null)
            {
                return;
            }
            cbStart.Checked = settings.IsAutoStart;
        }

        private void cbStart_CheckedChanged(object sender, EventArgs e)
        {
            RunWhenStart(cbStart.Checked, "Koala.JiraTool", Application.ExecutablePath);
        }

        /// <summary>
        /// 开机启动项
        /// </summary>
        /// <param name="started">是否启动</param>
        /// <param name="name">启动值的名称</param>
        /// <param name="path">启动程序的路径</param>
        public void RunWhenStart(bool started, string name, string path)
        {
            var settings = new Settings { IsAutoStart = started };
            var hklm = Registry.LocalMachine;
            var run = hklm.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
            if (started)
            {
                try
                {
                    run.SetValue(name, path);
                    hklm.Close();
                    _dataPersistence.Save(settings);
                }
                catch (Exception exception)
                {
                    MessageBox.Show("设置开机启动失败，请尝试使用管理员身份运行，详细错误：" + exception, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                try
                {
                    run.DeleteValue(name);
                    hklm.Close();
                    _dataPersistence.Save(settings);
                }
                catch (Exception exception)
                {
                    MessageBox.Show("取消开机启动失败，请尝试使用管理员身份运行，详细错误：" + exception, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
}